package share.storage.io.exchange;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import org.dom4j.*;
import org.dom4j.io.*;
import share.storage.io.*;

public class ExFileLoader implements FileLoader {

	public File load(FileLoadParameter para) throws IOException {
		// download XML
		Document doc=null;
		try {
			doc = downloadXml(para.getLoadPath()+"/exchange.xml");
		} catch (DocumentException e) {
			throw new IOException("XML Document error,check it");
		}
		ExchangeXmlResolver resolver=new ExchangeXmlResolver(doc);
		resolver.locate("/");
		ExRootFile root=new ExRootFile();
		root.setHost(para.getLoadPath());
		root.setFileName(para.getName());
		for(Element e:resolver.getChildren()){
			root.addChild(ExFile.buildFile(e,root));
		}
		return root;
	}

	/**
	 * 下载XML文件,并生成XML文档.
	 */
	private static Document downloadXml(String uri) throws IOException, DocumentException {
		SAXReader sr = new SAXReader();
		URL url = null;
		url = new URL(uri);
		java.net.URLConnection conn = url.openConnection();
		Reader br = new BufferedReader(new InputStreamReader(
				conn.getInputStream(),"UTF-8"));
		Document doc= sr.read(br);
		br.close();
		return doc;
	}

}
